package org.example.innovate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.example.innovate.common.CommonResponse;
import org.example.innovate.domain.User;
import org.example.innovate.mapper.UserMapper;
import org.example.innovate.service.AliyunSendSmsService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

@RestController
@Valid
public class AliyunSendSmsController {
    @Resource
    AliyunSendSmsService aliyunSendSmsService;
    @Resource
    UserMapper userMapper;
    @Value("${aliyun.sms.templateCode}")
    private String templateCode;
    // 发送验证码
    @PostMapping("/VCode")
    public CommonResponse<String> sendVCode(@Validated @RequestBody User user) {
        String phone = user.getPhone();

        boolean isMatch = Pattern.matches("^1[3-9]\\d{9}$", phone);
        if (!isMatch) {
            return CommonResponse.createForError("请输入正确的电话号");
        }

        String code = AliyunSendSmsService.generateVerificationCode();
        // 验证码存入codeMap
        Map<String, Object> codeMap = new HashMap<>();
        codeMap.put("code", code);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        User user1 = userMapper.selectOne(queryWrapper);
        if (user1 == null) {
            user.setPassword(code);
            user.setVcode(code);
            user.setUsername(phone);
            System.out.println(user.getVcode());
            userMapper.insert(user);
        }else{
            user1.setVcode(code);
            userMapper.updateById(user1);
        }
        // 调用aliyunSendSmsService发送短信
        Boolean bool = aliyunSendSmsService.sendMessage(phone, templateCode, codeMap);

        if (bool) {
            // 如果发送成功，则将生成的4位随机验证码存入数据库
            // 打印验证码
            System.out.println(phone + " ： " + code + "发送成功！");
            return CommonResponse.createForSuccess("发送成功",code);
        } else {
            System.out.println(phone + " ： " + code + "发送失败！");
            return CommonResponse.createForError("发送失败");
        }
    }

}
